﻿using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Xna.Framework.Input.Touch;
using MvvmLightNavgation;
using System;
using Helper;
using Microsoft.Xna.Framework.Media;
using Model;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight.Command;

namespace DBFM7.ViewModel
{
    /// <summary>
    /// MainPage ViewModel
    /// createby:kklldog
    /// date:20120304
    /// </summary>
    public class MainPageViewModel : ViewModelBase, INavigation
    {
        /// <summary>
        /// Initializes a new instance of the MainPageViewModel class.
        /// </summary>
        public MainPageViewModel()
        {
            NavigationHelper.NavigatedMsgReg(this);

            this.PlayCommand = new RelayCommand(this.Play);
            this.NextCommand = new RelayCommand(this.Next);
            this.FavCommand = new RelayCommand(this.AddFavSong);
            this.BackKeyPressCommand = new RelayCommand<System.ComponentModel.CancelEventArgs>(BackKeyPress);
            this.ChannelNameDoubleTapCommand = new RelayCommand(ChannelNameDoubleTap);
            this.ManipulationStartedCommand = new RelayCommand<ManipulationStartedEventArgs>( ManipulationStarted);
            this.ManipulationCompletedCommand = new RelayCommand<ManipulationCompletedEventArgs>(ManipulationCompleted);

            PlayListHelper.ReFreshComplete += new Action(PlayListHelper_ReFreshComplete);
            MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
            _timer.Interval = TimeSpan.FromMilliseconds(500);
            _timer.Tick += new EventHandler(_timer_Tick);

        }

        private ChannelType _CurrentChannel = ChannelType.None;
        private bool IsUserPaused = false;
        private DispatcherTimer _timer = new DispatcherTimer();
        private dbSong CurrentSong
        {
            get
            {
                if (PlayListHelper.pl.song.Count <= PlayListHelper.SongIndex)
                    return null;
                return PlayListHelper.pl.song[PlayListHelper.SongIndex];
            }
        }

        #region 属性

        private string _ChannelName;
        /// <summary>
        /// 频道名称
        /// </summary>
        public string ChannelName
        {
            get { return _ChannelName; }
            set { _ChannelName = value;
            this.RaisePropertyChanged("ChannelName");
            }
        }

        private string _PlayTime;
        /// <summary>
        /// 播放时间
        /// </summary>
        public string PlayTime
        {
            get { return _PlayTime; }
            set { _PlayTime = value;
            this.RaisePropertyChanged("PlayTime");
            }
        }

        private string _SongInfo;
        /// <summary>
        /// 歌曲信息
        /// </summary>
        public string SongInfo
        {
            get { return _SongInfo; }
            set { _SongInfo = value;
            this.RaisePropertyChanged("SongInfo");
            }
        }

        private BitmapImage _SongImg;
        /// <summary>
        /// 歌曲封面URI
        /// </summary>
        public BitmapImage SongImg
        {
            get { return _SongImg; }
            set { _SongImg = value;
            this.RaisePropertyChanged("SongImg");
            }
        }

        private Uri _BtnPlayIcon = new Uri("/ICON/appbar.transport.play.rest.png",UriKind.Relative);

        public Uri BtnPlayIcon
        {
            get { return _BtnPlayIcon; }
            set { _BtnPlayIcon = value;
            this.RaisePropertyChanged("BtnPlayIcon");
            }
        }
        private Uri _BtnFavIcon = new Uri("/ICON/appbar.favs.addto.rest.png", UriKind.Relative);

        public Uri BtnFavIcon
        {
            get { return _BtnFavIcon; }
            set { _BtnFavIcon = value;
            this.RaisePropertyChanged("BtnFavIcon");
            }
        }

        private string _PlayBtnText="播放";

        public string PlayBtnText
        {
            get { return _PlayBtnText; }
            set { _PlayBtnText = value;
            this.RaisePropertyChanged("PlayBtnText");
            }
        }

        #endregion 

        #region Command

        private RelayCommand _PlayCommand;

        public RelayCommand PlayCommand
        {
            get { return _PlayCommand; }
            set { _PlayCommand = value;
            this.RaisePropertyChanged("PlayCommand");
            }
        }

        private RelayCommand _FavCommand;

        public RelayCommand FavCommand
        {
            get { return _FavCommand; }
            set { _FavCommand = value;
            this.RaisePropertyChanged("FavCommand");
            }
        }


        private RelayCommand _NextCommand;

        public RelayCommand NextCommand
        {
            get { return _NextCommand; }
            set { _NextCommand = value;
            this.RaisePropertyChanged("NextCommand");
            }
        }

        private RelayCommand<System.ComponentModel.CancelEventArgs> _BackKeyPressCommand;
        public RelayCommand<System.ComponentModel.CancelEventArgs> BackKeyPressCommand
        {
            get { return _BackKeyPressCommand; }
            set { _BackKeyPressCommand = value;
            this.RaisePropertyChanged("BackKeyPressCommand");
            }
        }


        private RelayCommand _ChannelNameDoubleTapCommand;
        public RelayCommand ChannelNameDoubleTapCommand
        {
            get { return _ChannelNameDoubleTapCommand; }
            set { _ChannelNameDoubleTapCommand = value;
            this.RaisePropertyChanged("ChannelNameDoubleTapCommand");
            }
        }

        private RelayCommand<ManipulationCompletedEventArgs> _ManipulationCompletedCommand;
        public RelayCommand<ManipulationCompletedEventArgs> ManipulationCompletedCommand
        {
            get { return _ManipulationCompletedCommand; }
            set
            {
                _ManipulationCompletedCommand = value;
                this.RaisePropertyChanged("ManipulationCompletedCommand");
            }
        }


        private RelayCommand<ManipulationStartedEventArgs> _ManipulationStartedCommand;
        public RelayCommand<ManipulationStartedEventArgs> ManipulationStartedCommand
        {
            get { return _ManipulationStartedCommand; }
            set
            {
                _ManipulationStartedCommand = value;
                this.RaisePropertyChanged("ManipulationStartedCommand");
            }
        }

        #endregion

        private  void ChannelNameDoubleTap()
        {
            NavigationHelper.NavigationMsgSend("/View/ChannelTile.xaml");
        }

        private void BackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            NavigationHelper.NavigationMsgSend("/View/ChannelTile.xaml");
        }

        private void Play()
        {
            if (MediaPlayer.State == MediaState.Stopped)
            {
                this.Play(CurrentSong);
                this.IsUserPaused = false;
                ChangeBtnImg("pause");
            }
            else if (MediaPlayer.State == MediaState.Paused)
            {
                MediaPlayer.Resume();
                this.IsUserPaused = false;
                ChangeBtnImg("pause");
            }
            else
            {
                MediaPlayer.Pause();
                this.IsUserPaused = true;
                ChangeBtnImg("play");
            }
        }

        private void Next()
        {
            PlayListHelper.SongIndex++;
            if (CurrentSong == null)
            {
                PlayListHelper.ReFresh(this._CurrentChannel);
            }
            else
            {
                this.Play(CurrentSong);
            }
        }


        private void PlayListHelper_ReFreshComplete()
        {
            this.Play(CurrentSong);
        }

        private void AddFavSong()
        {
            if (this.CurrentSong == null)
                return;

            if (!DbHelper.IsFavSong(this.CurrentSong))
            {
                DbHelper.AddFavSong(this.CurrentSong);
                this.ChangeBtnImg("fav");
            }
            else
            {
                DbHelper.DelFavSong(this.CurrentSong);
                this.ChangeBtnImg("fav_addto");
            }
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            if (MediaPlayer.State == MediaState.Playing)
            {
                this.PlayTime = string.Format("{0:00}:{1:00}", MediaPlayer.PlayPosition.Minutes, MediaPlayer.PlayPosition.Seconds);
            }
            if (MediaPlayer.State == MediaState.Stopped)
            {
                this.PlayTime = "";
                _timer.Stop();
            }
        }

        private void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
        {
            if (MediaPlayer.State == MediaState.Paused)
            {
                if (!this.IsUserPaused)
                {
                    this.Next();
                }

            }
        }

        private void ChangeBtnImg(string type)
        {
            string url_play = "/ICON/appbar.transport.play.rest.png";
            string url_pause = "/ICON/appbar.transport.pause.rest.png";
            string url_fav = "/ICON/appbar.favs.rest.png";
            string url_fav_addto = "/ICON/appbar.favs.addto.rest.png";
            if (type == "play")
            {
               this.BtnPlayIcon = new Uri(url_play, UriKind.RelativeOrAbsolute);
               this.PlayBtnText = "播放";
            }
            else if (type == "pause")
            {
                this.BtnPlayIcon = new Uri(url_pause, UriKind.RelativeOrAbsolute);
                this.PlayBtnText = "暂停";
            }
            else if (type == "fav")
            {
                this.BtnFavIcon = new Uri(url_fav, UriKind.RelativeOrAbsolute);
            }
            else if (type == "fav_addto")
            {
                this.BtnFavIcon = new Uri(url_fav_addto, UriKind.RelativeOrAbsolute);
            }
        }


        private void Play(dbSong song)
        {
            MediaPlayer.Stop();
            this.SongImg = null;
            if (song == null)
            {
                this.SongInfo = "No Song！";
                this.SongImg = null;
                return;
            }
            if (DbHelper.IsFavSong(song))
            {
                this.ChangeBtnImg("fav");
            }
            else
            {
                this.ChangeBtnImg("fav_addto");
            }
            Song s = Song.FromUri(song.title, new Uri(song.url));
            MediaPlayer.Play(s);
            DbHelper.DelSong(song);
            this.SongInfo = song.artist + "-" + song.title;
            Messenger.Default.Send("ChangeSongInfo");
            this.SongImg = new BitmapImage(new Uri(song.picture, UriKind.Absolute));
            this.ChangeBtnImg("pause");
            _timer.Start();
        }

        public string GetViewUrl()
        {
            return "/View/MainPage.xaml";
        }

        public void Navigated(System.Uri uri)
        {
            if (NavigationHelper.GetQueryString(uri, "Channle")=="")
            {
                this.ChannelName = PlayListHelper.CurrentChannel.ToString();
      
                return;
            }

            string ch = NavigationHelper.GetQueryString(uri, "Channle");
            var chn = this.GetChannelType(ch);
            this.ChannelName = ch;
            if (PlayListHelper.CurrentChannel == chn)
            {
 
                return;
            }
            _CurrentChannel = chn;
            PlayListHelper.ReFresh(_CurrentChannel);
        }

 

        private ChannelType GetChannelType(string channel)
        {
            ChannelType ct = (ChannelType)Enum.Parse(typeof(ChannelType), channel, false);
            return ct;
        }


        System.Windows.Point pFirst;
        System.Windows.Point pSecond;
        private void ManipulationCompleted(ManipulationCompletedEventArgs e)
        {
            pSecond = e.ManipulationOrigin;
            bool IsDo = false;
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                //如果是水平手势 起始点的X>结束点的X
                if (gesture.GestureType == GestureType.HorizontalDrag && pFirst.X < pSecond.X && !IsDo)
                {
                    IsDo = true;
                    this.Next();

                }
            }

        }

        private void ManipulationStarted(ManipulationStartedEventArgs e)
        {
            pFirst = e.ManipulationOrigin;
        }

    }
}